#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

float* work;
int size;
float tol;

#pragma omp threadprivate(work, size, tol)

void build() {
    int i;
    work = (float*)malloc(sizeof(float) * size);
    for (i = 0; i < size; ++i) work[i] = tol;
}

void copyin_example(float t, int n) {
    tol = t;
    size = n;
    #pragma omp parallel copyin(tol, size)
    {
        build();
        
        // 验证每个线程的work数组是否正确初始化
        int tid = omp_get_thread_num();
        int i;
        int correct = 1;
        
        for (i = 0; i < size; i++) {
            if (work[i] != tol) {
                correct = 0;
                break;
            }
        }
        
        #pragma omp critical
        {
            printf("线程 %d: work数组%s正确初始化 (tol = %.1f, size = %d)\n", 
                  tid, correct ? "已" : "未", tol, size);
        }
        
        // 释放该线程的work内存
        free(work);
    }
}

int main() {
    printf("开始OpenMP并行程序验证...\n");
    
    // 设置线程数
    int num_threads = 4;
    omp_set_num_threads(num_threads);
    
    printf("使用 %d 个线程运行\n", num_threads);
    
    // 测试参数
    float test_tol = 3.14;
    int test_size = 1000;
    
    // 运行copyin_example函数
    printf("调用copyin_example(%.2f, %d)\n", test_tol, test_size);
    copyin_example(test_tol, test_size);
    
    // 再次运行，使用不同的参数
    test_tol = 2.71;
    test_size = 500;
    printf("\n调用copyin_example(%.2f, %d)\n", test_tol, test_size);
    copyin_example(test_tol, test_size);
    
    printf("\n验证完成！\n");
    return 0;
}